import React, { useEffect, useState } from "react";
import { Button, Form, Input, message, Modal, Space, Upload } from "antd";
import { RcFile, UploadProps } from "antd/es/upload/interface";
import { UploadChangeParam } from "antd/es/upload";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";

type ProductSetModalProps = {
    modalTitle: string;
    modalVisible: boolean;
    setModalVisible: (visible: boolean) => void;
    modalData: any;
    handleOk: (values: any) => void;
};

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
        message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
};

function ProductSetModal(props: ProductSetModalProps) {
    const [form] = Form.useForm(); // 表单实例

    // 上传图片相关
    const [loading, setLoading] = useState(false);
    const [logoUrl, setLogoUrl] = useState<string>();

    const handleChange: UploadProps["onChange"] = (info: UploadChangeParam) => {
        if (info.file.status === "uploading") {
            setLoading(true);
            return;
        }
        if (info.file.status === "done") {
            setLogoUrl(info.file.response.data);
            setLoading(false);
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    // 判断是添加还是修改
    useEffect(() => {
        // 判断modalData是否有值，有值就是修改，没有值就是添加
        if (props.modalData) {
            if (props.modalData.id) {
                // 修改
                form.setFieldsValue(props.modalData); // 设置表单数据
                setLogoUrl(props.modalData.logoUrl); // 设置图片
            } else {
                // 添加
                form.resetFields(); // 重置表单数据
            }
        }
    }, [props.modalData]);

    return (
        <div>
            <Modal
                title={props.modalTitle} // modal的标题
                visible={props.modalVisible} // 控制modal的显示与隐藏
                footer={null} // 不显示modal的底部按钮
                forceRender // 强制渲染
                onCancel={() => {
                    props.setModalVisible(false); // 关闭modal
                    // 重置表单数据
                    form.resetFields();
                    // 重置图片
                    setLogoUrl("");
                }}
            >
                <Form
                    name="basic"
                    form={form}
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    autoComplete="off"
                    onFinish={async (values) => {
                        const { tmName, logoUrl } = values;
                        props.handleOk({
                            id: props.modalData?.id || "",
                            tmName,
                            logoUrl: logoUrl[0].response.data,
                        });
                        // 重置表单数据
                        form.resetFields();
                        // 重置图片
                        setLogoUrl("");
                        props.setModalVisible(false); // 关闭modal
                        message.success(props.modalTitle + "成功");
                    }}
                >
                    <Form.Item label="品牌名称" name="tmName" rules={[{ required: true, message: "请输入品牌名称" }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="品牌LOGO"
                        name="logoUrl"
                        rules={[{ required: true, message: "请上传品牌LOGO" }]}
                        valuePropName={props.modalData && props.modalData.id ? "logoUrl" : "fileList"}
                        getValueFromEvent={(e) => {
                            if (Array.isArray(e)) {
                                return e;
                            }
                            return e && e.fileList;
                        }}
                    >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {logoUrl ? <img src={logoUrl} alt="avatar" style={{ width: "100%" }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 8, span: 19 }}>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button
                                htmlType="button"
                                onClick={() => {
                                    form.resetFields(); // 清空表单
                                    // 重置图片
                                    setLogoUrl("");
                                }}
                            >
                                清空
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}

export default ProductSetModal;
